
package edu.weber.bookstore.controllers;

import edu.weber.bookstore.database.Book;
import edu.weber.bookstore.models.BookViewModel;
import edu.weber.bookstore.models.BooksIndexModel;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * 
 */
public class BooksController extends AppController
{
	/**
	 * Home page of website
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/books/index", method=RequestMethod.GET)
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		return new ModelAndView("books/index", "model", null);
	}
	
	/**
	 * Book view page
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/books/view/", method=RequestMethod.GET)
	public ModelAndView view(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		int book_id = Integer.parseInt(request.getParameter("id"));
		BookViewModel bvm = new BookViewModel(Book.find(book_id));
		return new ModelAndView("books/view", "model", bvm.getMap());
	}
	
	/**
	 * Book search page
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/books/search")
	public ModelAndView search(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String search = request.getParameter("field");
		String value = request.getParameter("value");
		boolean isPost = request.getMethod().equalsIgnoreCase("POST");
		List<Book> books = (List<Book>)new ArrayList<Book>();
		
		if(search != null && value != null)
		{
			if(search.equalsIgnoreCase("author"))
			{
				books = Book.searchBookByAuthor(value);
			}
			else if(search.equalsIgnoreCase("title"))
			{
				books = Book.searchBookByTitle(value);
			}
			else if(search.equalsIgnoreCase("isbn"))
			{
				Book book = Book.findBookByIsbn(value);
				if(book != null)
				{
					books.add(book);
				}
			}
			else if(search.equalsIgnoreCase("desc"))
			{
				books = Book.searchBookByDescription(value);
			}
		}
		else
		{
			books = Book.select();
		}
		
		BooksIndexModel blm = new BooksIndexModel(books);
		
		return new ModelAndView("books/search", "model", blm.getMap());
	}
}
